package com.oauth.global.client.ui.feeds;

import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.Widget;
import com.oauth.components.client.rpc.OAuthAsnyCallBack;
import com.oauth.components.client.ui.HasInit;
import com.oauth.components.client.ui.HasWidgetInfo;
import com.oauth.global.client.beans.ApplicationClientBean;
import com.oauth.global.client.rpc.GlobalRemoteServiceAsync;

public class FeedsPanel extends Composite {

	private static FeedsPanelUiBinder uiBinder = GWT
			.create(FeedsPanelUiBinder.class);

	interface FeedsPanelUiBinder extends UiBinder<Widget, FeedsPanel> {
	}

	@UiField
	DecoratedTabPanel tabPanel;
	
	@UiField
	DeckPanel deckPanel;

	private Map<Long, HasWidgetInfo> widgetMap;

	public FeedsPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
			
			@Override
			public void onSelection(SelectionEvent<Integer> event) {
				Integer selectedItem = event.getSelectedItem();
				HasInit hasInit = (HasInit)tabPanel.getWidget(selectedItem);
				hasInit.init();
				
			}
		});
	}

	/**
	 * @param widgetMap
	 *            the widgetMap to set
	 */
	public void setWidgetMap(Map<Long, HasWidgetInfo> widgetMap) {
		this.widgetMap = widgetMap;
	}

	public void clearAll() {
		tabPanel.clear();
	}

	
	public void init() {
		clearAll();
		deckPanel.showWidget(0);

		GlobalRemoteServiceAsync.INSTANCE
				.getApplicationForFeeds(new OAuthAsnyCallBack<List<ApplicationClientBean>>() {

					@SuppressWarnings("deprecation")
					@Override
					public void onSuccess(List<ApplicationClientBean> pAppInfoList) {
						if (pAppInfoList == null || pAppInfoList.isEmpty()) {
							deckPanel.showWidget(1);
						} else {
							deckPanel.showWidget(2);
							for (ApplicationClientBean infoBean : pAppInfoList) {
								String appName = widgetMap.get(infoBean.getId()).getName();
								tabPanel.add(new FeedTab(infoBean.getId()), appName);
							
							}
						}
					}
				});
	}

	
}
